package SharedDrawing;

/*
 * This file is part of shared-drawing.
 * shared-drawing is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option )
 * any later version. shared-drawing is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * You should have received a copy of the GNU General Public License along with 
 * shared-drawing. If not, seehttp://www.gnu.org/licenses/.
 */

import common.XmlConstants;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/*
 * FAIRE UN SINGLETON
 */

/**
 * Manage file's input and output with pages
 * 
 */
public class XmlFile {
    
    /**
     * save all given pages in the given file (XML)
     * @param pathName the file
     * @param pages the list of pages
     * @return true on success
     */
    private static XmlFile instance;
    
    public static XmlFile getInstance(){
        if(instance == null)
            instance = new XmlFile();
        return instance;
    }
    
    public boolean save(File pathName, List<Page> pages)
    {
        Document doc = XmlGenerator.toXml(pages);
        //save
        XMLOutputter out = new XMLOutputter();
        java.io.FileWriter writer;
        try {
            writer = new java.io.FileWriter(pathName);
            out.output(doc, writer);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            System.out.println(e.toString());
            return false;
        }
        return true;
    }
    
    /**
     * upload a page from the given file
     * @param pathName the XML file that contains some pages
     * @return true on success
     */
    public boolean upload(File pathName)
    {
        SAXBuilder sxb = new SAXBuilder();
        Document doc;
        try
        {
            doc = sxb.build(pathName);
            List<ShapeContent> toDraw = new LinkedList();
            //Integer lastId = Integer.parseInt(doc.getRootElement().
              //      getAttributeValue(XmlConstants.pageCollectionLastId));
            //TODO : make something with this id
            //for each page-
            List<Element> list = doc.getRootElement().getChildren(XmlConstants.createPage);
            while(!list.isEmpty())
            {
                Element element = list.get(0);
                XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
                String string = outputter.outputString(doc);
                System.out.println("doc1 : " +string);
                //find a free number in the historic
                String id = Pages.getInstance().getFreeNumber();
                //set the page's attribut to this free
                element.setAttribute(XmlConstants.pageOld, id);
                //get the drawing of the page
                Element drawing = element.getChild(XmlConstants.createDrawing);
                if(drawing == null)
                {
                    System.out.println("wrong XML file, no drawing found");
                    return false;
                }
                drawing.setAttribute(XmlConstants.drawingId, "1");
                //for each shape
                for(Element child : drawing.getChildren(XmlConstants.shapeContent))
                {
                    toDraw.add(XmlGenerator.fromXml(child));
                    
                }
                //draw
                String pageName = element.getAttributeValue(XmlConstants.pageName);
                Page page = Pages.getInstance().createPageFromUpload(Integer.parseInt(id), 
                        pageName, 
                        ConnexionManager.getInstance().getUserId());
                element.detach();
                if(page != null)
                {
                    String name = page.getName();
                    element.removeAttribute(XmlConstants.pageName);
                    element.setAttribute(XmlConstants.pageName, name);
                    page.draw(toDraw);
                    toDraw.clear();
                    //send to the work group
                    SocketClient socket = SocketClient.getInstance();
                    if(socket != null)
                    {
                        socket.sendData(new Document(element));
                    }
                }
            }
        }
        catch(Exception e)
        {
            System.out.println("error while uploading a file on child : "
                    + e.toString());
            //Logger.getLogger(XmlFile.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }
        return true;
    }
    
    
}
